import { ElMessage,ElLoading } from "element-plus"
import { onMounted, ref, computed } from "vue"
import api from "../api/api"
// 引入保存二进制文件的插件
import { saveAs } from 'file-saver'
import axios from 'axios'
// 接收请求地址和筛选的值名称
// 函数为传递过来的值做修改
export default function useList(listRequestUrl,
	 fliterKey,
	 transformFn,
	 downloadUrl,
	 fileName) {
	// 分页数据
	const total = ref(0),
		pageNum = ref(1),
		pageSize = ref(10),
		// 加载状态
		loading = ref(false),
		// 原始数据
		list = ref([]),
		// 重新获取数据
		reload = () => {
			loadData()
		},
		// 搜索对应内容
		search = ref(""),
		// 计算属性为需要显示的数据
		// fliterKey 为需要进行筛选的列名称
		filterTableData = computed(() => {
			let data = list.value.filter(
				(x) =>
					!search.value ||
					x[fliterKey].toLowerCase().includes(search.value.toLowerCase())
			)
			total.value = data.length
			// 因为对应的接口暂未实现分页效果 所以暂时以切片替代
			if (data.length > 10) {
				return data.slice(
					(pageNum.value - 1) * pageSize.value,
					pageNum.value * pageSize.value
				)
			}
			return data
		}),
		// 请求数据
		loadData = async () => {
			loading.value = true
			try {
				const res = await api.get(listRequestUrl)
				list.value = res.data.rows || res.data.data
				// 当接收的数据需要转化时才会转化
				if (transformFn) {
					list.value = transformFn(list.value)
				}
				total.value = list.value.length
				ElMessage.success("获取成功!")
			} catch (error) {
				ElMessage.error("获取失败!")
			} finally {
				loading.value = false
			}
		},
		// 分页函数
		handleSizeChange = (val) => {
			pageSize.value = val
			console.log(`每页 ${val} 条`)
		},
		handleCurrentChange = (val) => {
			pageNum.value = val
		}
	// 下载Excel文件
	const http = axios.create({ baseURL: "http://43.138.224.168:3000" })
	// const http = axios.create({ baseURL: "http://localhost:3000" })
	const serverDataToExcel = async () => {
		// 显示全页加载态
		const loading = ElLoading.service({
			lock: true,
			text: "Loading",
			background: "rgba(0, 0, 0, 0.7)"
		})
		let response
		try {
			response = await http.get(downloadUrl, {
				responseType: "blob",
				headers: {
					Authorization: sessionStorage.getItem("token")
				}
			})
		}catch (err) {
			loading.close()
			return ElMessage.error("下载失败")
		}
		// 保存接收到的文件
		saveAs(response.data, `${fileName}.xlsx`)
		// 关闭加载态
		loading.close()
	}
	// 挂载时请求数据
	onMounted(() => {
		loadData()
	})

	//  导出必要内容
	return {
		loading,
		reload,
		pageNum,
		pageSize,
		total,
		search,
		filterTableData,
		handleSizeChange,
		handleCurrentChange,
		serverDataToExcel
	}
}
